package com.vip.mongofile.service.impl;

import com.vip.common.response.ErrorCode;
import com.vip.common.response.Result;
import com.vip.common.response.Results;
import com.vip.mongofile.constant.FileStorageEnum;
import com.vip.mongofile.dao.FileRepository;
import com.vip.mongofile.model.MongoFile;
import com.vip.mongofile.util.MD5Util;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.Binary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Optional;

/**
 * @Description:
 * @Date: 2020/12/03 17:44
 * @Author: wp
 **/
@Slf4j
@Service(value = "mongoFileStorage")
@RequiredArgsConstructor
public class MongoFileStorageServiceImpl extends AbstractFileStorageService {

    private final FileRepository fileRepository;

    @Override
    @SneakyThrows
    public Result<MongoFile> saveFile(MultipartFile file) {
        try {
            if (StringUtils.isEmpty(file.getOriginalFilename())) {
                throw new IllegalArgumentException("文件名不能为空");
            }
            MongoFile mongoFile = new MongoFile(file.getOriginalFilename(), file.getContentType(), file.getSize(), new Binary(file.getBytes()));
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            mongoFile.setContent(new Binary(file.getBytes())).setMd5(MD5Util.getMD5(file.getInputStream()))
                    .setUploadDate(new Date()).setSuffix(suffix);
            return Results.newSuccessResult(fileRepository.save(mongoFile));
        } catch (Exception e) {
            log.error("文件上传出错", e);
        }
        return Results.newFailResult(ErrorCode.FILE_ERROR, "上传失败");
    }

    @Override
    public Result<String> removeFile(String id) {
        try {
            fileRepository.deleteById(id);
            return Results.newSuccessResult(null, "删除成功");
        } catch (Exception e) {
            log.error("文件删除出错", e);
        }
        return Results.newFailResult(ErrorCode.FILE_ERROR, "删除失败");
    }

    @Override
    public Result<MongoFile> getFileById(String id) {
        try {
            Optional<MongoFile> result = fileRepository.findById(id);
            return result.map(mongoFile -> Results.newSuccessResult(mongoFile, "查询成功"))
                    .orElseGet(() -> Results.newFailResult(ErrorCode.DATA_NONE, "文件不存在"));
        } catch (Exception e) {
            log.error("获取文件详情出错", e);
        }
        return Results.newFailResult(ErrorCode.FILE_ERROR, "查询失败");
    }

    @Override
    public FileStorageEnum getEnumType() {
        return FileStorageEnum.MONGO;
    }
}
